<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/9
 * Time: 16:35
 */

namespace App\Api\Admin\Controllers;


use App\Exceptions\ApiException;
use App\Jobs\Elesticsearch;
use App\Models\MemberShip;
use App\Models\Shareholder;
use App\Models\User;
use APP\Models\Media;
use App;
use App\Models\Admin\Log;
use App\Models\UserReport;
use App\Models\ActivityConfig;
use App\Models\AffiliAtion;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Services\InviteSettlementService;
use App\Models\InviteSettlement;
use App\Models\InviteSettlementCollect;
use App\Models\AdminUser;
use App\Models\InviteRelationLog;
use App\Models\UserInvitationCode;
use App\Models\RandDigitalPool;

class UserController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 用户发布的视频
     */
    public function details(Request $request){
        $user_id = IT('user_id',true, '请输入用户ID');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
        $total = D('media')->where(['uid'=>$user_id ,'is_delete'=>0, 'status'=>1 ])->count();
        $totalPage = ceil($total / $pagesize);
        $lists =  D('media')->where(['uid'=>$user_id ,'is_delete'=>0, 'status'=>1 ])->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get(['id','uid','title','media','date','cover','video_length']);

        // 获取内网视频图片链接
        $datetime = new DateTime();
        $datetime->modify('+1 day');
        foreach ($lists as &$list) {
            $list->media = getSignUrl($list->media);
            $list->cover = getSignUrl($list->cover);
        }
        unset($list);
        return json_success('ok',['total'=>$total,'totalPage'=>$totalPage,'list' => $lists]);
    }

    /**
     * 用户列表
     * @param Request $request
     * @return array
     */
    public function artnerlLists(Request $request)
    {
        $user_id = $request->input('user_id');
        $name = replace_specialChar($request->input('name'));
        $role = (int)trim($request->input('role'));
        $membership = (int)trim($request->input('membership'));
        $mobile = $request->input('mobile');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize');
        $pagesize = $pagesize ?: 10;
        $offset = ($page - 1) * $pagesize;
         if($role !==0){
             $where =  ['status'=>1, 'role'=>$role] ;
         }else{
             $where =  ['status'=>1];
         }
         if($membership !== 0){
             $where =  ['status'=>1, 'membership'=>$membership] ;
         }
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        if($user_id){
            $where[] = ['id', 'like', '%' . $user_id . '%'];
        }
        if($mobile){
            $where[] = ['mobile', 'like', '%' . $mobile . '%'];
        }
        $users = User::where($where)->skip($offset)->take($pagesize)->orderBy('id', 'desc')->get(['id', 'name', 'real_name', 'mobile', 'avatar', 'email', 'sex', 'isconfirmed', 'created_at', 'updated_at', 'praise', 'attention', 'fans','role','membership','ascription']);
      // 获取内网视频图片链接
        foreach ($users as &$list) {
            $ascription_name = AffiliAtion::where(['id'=>$list->ascription,'status'=>0])->value('locality_name');
            $list->avatar = getSignUrl($list->avatar);
            $list->works  = D('media')->where(['uid'=>$list->id ,'is_delete'=>0, 'status'=>1 ])->count();
            $list->ascription_name  = !empty($ascription_name) ? $ascription_name : '';
        }
        unset($list);
        $total =  User::where($where)->count();
        $totalPage = ceil($total / $pagesize);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $users]);
    }
    /**
     * 添加股东搜索列表
     */
    public function  ArtnerlData(Request $request){
       $user_id = IT('user_id');
       $mobile = IT('mobile');
       $role = (int)trim($request->input('role'));
        if($role !==0){
            $where =  ['status'=>1, 'role'=>$role] ;
        }else{
            $where =  ['status'=>1];
        }
       $data =  User::orWhere('id','=',$user_id)->where($where)->orWhere('mobile','=',$mobile)->get(['id', 'name', 'real_name', 'mobile', 'avatar', 'email', 'sex', 'isconfirmed', 'created_at', 'updated_at', 'praise', 'attention', 'fans','role']);
        return json_success('ok',$data);
    }
    /**
     * 添加用户(平台用户添加)
     * @param Request $request
     * @return array
     */
    public function  Addartnerl(Request $request){
        $user_id = IT('user_id',true,'请输入微影号');
        $role = IT('role',true,'请输入角色');
        switch ($role) {
            case 1:
                $role_type = '股东用户';
                break;
            case 2:
                $role_type = '客服';
                break;
            case 3:
                $role_type = '营销';
                break;
            default:
                $role_type = '普通用户';
                break;
        }
        $add_data =  User::where('id','=',$user_id)->update(['role'=>$role]);
        $lower_data = D('admin_users')->where('id','=',$this->user['id'])->value('lower_user');
        if($add_data){
            if($role > 1){
                D('admin_users')->where('id','=',$this->user['id'])->update(['lower_user'=>$user_id .','.$lower_data]);
            }
            (new Log)->add($this->user, '添加了【'.$user_id.'】为'.$role_type);
            return json_success('ok',$add_data);
        }else{
            return json_error('添加失败');
        }
    }
    /**
     * 添加用户(创建新用户)
     * @return array
     * @throws \Exception
     */
    public function AddUser(){
        $mobile = IT('mobile',true,'请输入手机号码');
        $password = IT('password',true,'请输入密码');
        $role = (int) IT('role',true,'请输入角色ID');
        $name = IT('name',true,'添加用户昵称');
        $sex = IT('sex',true,'请选择用户性别');
        if(!preg_match("/^\\d{11}$/",$mobile)){
            return json_error('手机号必须为11位数字');
        }
        if(!check_password_format($password)){
            return json_error('密码必须是6-16位字母数字下划线组合');
        }
        $user = DB::table('users')->where('mobile', $mobile)->first();//注册人信息
        if($user){
            return json_error('该帐号['.$mobile.']已存在');
        }
        if($role <= 1 && $role > 3){
            return json_error('请查看你添加的角色是否正确');
        }
        switch ($role) {
            case 2:
                $role_type = '客服';
                break;
            case 3:
                $role_type = '营销';
                break;
            default:
                $role_type = '普通用户';
                break;
        }
        $userInfo = [
            'mobile' => $mobile,
            'name' => $name,
            'password' => md5($password),
            'sex' => $sex,
            'status' => 1,
            'avatar'=> '',
            'created_at'    =>  date('Y-m-d H:i:s'),
            'updated_at'    =>  date('Y-m-d H:i:s'),
            'role' => $role
        ];
        $uid = DB::table('users')->insertGetId($userInfo);//插入成功返回id值
        $lower_data = D('admin_users')->where('id','=',$this->user['id'])->value('lower_user');
        if ($uid) {
            //TODO 添加成功将UID更新到user_tags表
            $tags_data =[
                'uid' => $uid,
            ];
            DB::table('user_tags')->insert($tags_data);
            D('admin_users')->where('id','=',$this->user['id'])->update(['lower_user'=> $uid .','.$lower_data]);
            //生成ticket入库
            $ticket = get_ticket($uid);
            if ($ticket) {
                // 队列   --添加搜索索引
                $params['uid'] = $uid;
                $params['name'] = $name;
                $params['mobile'] = $mobile;
                dispatch((new Elesticsearch(['type'=>'1', 'action'=>'add', 'data'=>$params]))->onQueue('eleasticsearch'));
                //新账号生成邀请码
                $number = RandDigitalPool::where('status','=',0)->orderBy('id','ASC')->first(['id','number']);
                $InvitationCode= UserInvitationCode::insert(['uid'=>$uid,'invitation_code'=>$number->number]);
                if($InvitationCode){
                    RandDigitalPool::where('id','=',$number->id)->update(['status'=>1]);
                }
                (new Log)->add($this->user, '添加了用户【'.$uid.'】角色为-'.$role_type);
                return json_success('ok',['ticket' => $ticket, 'uid' => $uid]);
            }
        }else{
            return json_error('添加失败');
        }
    }

    /**
     * @return array
     * 删除用户
     */
    public function DelUser(){
        $uid = IT('uid',true,'请填写用户ID');
        $chk_user= User::where('id',$uid)->where('status','<>',0)->first();
        $role =$chk_user['role'];
         if(!$chk_user){
             return json_error('用户不存在');
         }
        switch ($role) {
            case 1:
                $role_type = '股东';
                break;
            case 2:
                $role_type = '客服';
                break;
            case 3:
                $role_type = '营销';
                break;
            default:
                $role_type = '普通用户';
                break;
        }
        $update_user = User::where('id',$uid)->update(['status'=>0]);
        if($update_user) {
            (new Log)->add($this->user, '删除了用户【' . $uid . '】角色为-' . $role_type);
            return json_success('ok');
        }else{
            return json_error('删除失败!');
        }
    }
    /**
     * @return array
     * 管理员下级用户
     */
    public function LowerUser(){
        $name  = IT('name');
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $id = $this->user['id'];
        $data = D('admin_users')->where('id','=',$id)->first();
        $arr =explode(",",$data->lower_user);
        if(!empty($name)){
            $list = User::where($where)->whereIn('id', $arr)->distinct()->get(['id','name','avatar']);
        }else{
            $list = User::whereIn('id', $arr)->distinct()->get(['id','name','avatar']);
        }
        return json_success('ok',$list);
    }

    /**
     * @param Request $request
     * @return array
     * 举报用户列表
     */
    public function ReportUserList(Request $request){
        $report_type = $request->input('report_type');
        $page = max(1, (int) $request->input('page'));
        $pageSize = (int) $request->input('pagesize');
        $pageSize = $pageSize ?: 10;
        $offset = ($page - 1) * $pageSize;
        if($report_type){
            $where =  ['wy_user_report.status'=>1, 'wy_user_report.report_type'=>$report_type] ;
        }else{
            $where =  ['wy_user_report.status'=>1];
        }
        $fields=['wy_user_report.id','wy_user_report.report_obj_id','wy_user_report.report_type','wy_user_report.content','wy_user_report.report_time', 'users.id as uid','users.name'];
        $user_data =UserReport::where($where)->leftjoin('users', 'users.id', '=', 'wy_user_report.report_obj_id')->skip($offset)->take($pageSize)->groupBy('wy_user_report.report_obj_id')->orderBy('id', 'desc')->get($fields);
        $total = UserReport::where($where)->leftjoin('users', 'users.id', '=', 'wy_user_report.report_obj_id')->groupBy('wy_user_report.report_obj_id')->count();
        $totalPage = ceil($total / $pageSize);
        foreach ($user_data as &$list) {
            $list->report_type = D('report_type')->where('id','=',$list->report_type)->value('name');
            $list->reports_number  = D('wy_user_report')->where('report_obj_id','=',$list->report_obj_id)->count();
        }
        unset($list);
        return json_success('ok',['total'=>$total,'totalPage' =>$totalPage, 'list' => $user_data]);
    }

    /**
     * @param Request $request
     * @return array
     * 举报用户详情
     */
    public function ReportUser(Request $request){
        $uid = IT('uid', true, '请输入uid');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pageszie');
        $pagesize = $pagesize ?: 3;
        $offset = ($page - 1) * $pagesize;
        $user_fields =['id','name','mobile','created_at','avatar','role'];
        $user_info = User::where('id','=',$uid)->get($user_fields );
        foreach ($user_info as &$K) {
            $K['avatar'] = getSignUrl($K['avatar']);
            $K['ReportNumber'] = UserReport::where('report_obj_id','=',$K->id)->count();;
            $K['reporttime'] = UserReport::where('report_obj_id','=',$K->id)->max('report_time');
        }
        unset($K);
        $fields=['wy_user_report.id','wy_user_report.report_type','wy_user_report.content','wy_user_report.uid','wy_user_report.report_time', 'users.id as userid'];;
        $lists = UserReport::join('users', 'users.id', '=', 'wy_user_report.report_obj_id')->where('wy_user_report.report_obj_id','=',$uid)->orderBy('id', 'desc')->skip($offset)->take($pagesize)->get($fields);
        $total = UserReport::join('users', 'users.id', '=', 'wy_user_report.report_obj_id')->where('wy_user_report.report_obj_id','=',$uid)->count();
        $totalPage = ceil($total / $pagesize);
        foreach ($lists as &$list) {
            $list->report_type = D('report_type')->where('id','=',$list->report_type)->value('name');
            $list->informant =User::where('id',$list->uid)->value('name');
        }
        unset($list);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage,'list' =>$lists,'user_info'=>$user_info]);
    }

    /**
     * 绑定/解绑 账号
     * */
    public function BindingAccount()
    {
        $admin_uid = IT('admin_uid',true,'未知管理员');
        $uid = IT('uid',true,'未知绑定用户');
        $status = IT('status',true,'未知操作状态');

        $adminRows = D('admin_users')->where('id','=',$admin_uid)->first();
        $usersRows = D('users')->where('id','=',$uid)->first();
        if(empty($adminRows))
            return json_error('管理员账号不存在');
        if(empty($usersRows))
            return json_error('用户不存在');

        $lower_user_arr = explode(',', $adminRows->lower_user);

        $optionLogStr = '账号绑定操作';
        switch ($status){
            case 1:
                $optionLogStr = '账号绑定';
                if(in_array($uid, $lower_user_arr))
                    return json_error('会员已绑定管理员账号，无需重复绑定');
                $lower_user_arr[] = $uid;
                break;
            case 2:
                $optionLogStr = '取消账号绑定';
                if(!in_array($uid, $lower_user_arr))
                    return json_error('会员未绑定管理员，无效操作');
                // 移除取消的元素
                $lower_user_arr = array_diff($lower_user_arr, [$uid]);
                break;
            default:
                return json_error('未知操作状态');
                break;
        }

        $updateResult = D('admin_users')->where('id','=',$adminRows->id)->update(['lower_user'=> empty($lower_user_arr) ? '' : trim(implode(',', $lower_user_arr), ',')]);
        if(!$updateResult)
            return json_error('账号绑定异常');

        (new Log)->add($this->user, $optionLogStr);
        return json_success('ok');
    }

    /**
     * 账号绑定-会员搜索
     *
     * */
    public function SearchAccount()
    {
        $admin_uid = IT('admin_uid',true,'未知管理员');
        $mobile = IT('mobile',true,'未知绑定用户');

        $adminRows = D('admin_users')->where('id','=',$admin_uid)->first();
        $userFeild = [DB::raw('id as uid'),'name','real_name','mobile','avatar','email','sex','isconfirmed','praise','attention','fans','role'];
        $usersRows = D('users')->select($userFeild)->where('mobile','=',$mobile)->first();

        if(!empty($usersRows)){
            if(empty($adminRows))
                return json_error('管理员账号不存在');
            if(empty($usersRows))
                return json_error('用户不存在');

            $usersRows->is_binding = 0;
            if(in_array($usersRows->uid, explode(',', $adminRows->lower_user)))
                $usersRows->is_binding = 1;

            return json_success('ok', [$usersRows]);
        }

        return json_error('数据不存在');
    }

    /**
     * 账号绑定列表
     * */
    public function BindingList()
    {
        $admin_uid = IT('admin_uid',true,'未知管理员');
        $page = IT('page');
        $pagesize = IT('pagesize');
        $offset = ($page - 1) * $pagesize;
        $adminRows = D('admin_users')->where('id','=',$admin_uid)->first();
        if(empty($adminRows))
            return json_error('管理员账号不存在');

        $pagesize = intval($pagesize) > 0 ? $pagesize : 10;
        $page = intval($page) > 0 ? $page-1 : 0;
        $lower_user_arr = explode(',', $adminRows->lower_user);

       // $uidArr = array_slice($lower_user_arr, $page * $pageSize, $pageSize);
        $userFeild = [DB::raw('id as uid'),'name','real_name','mobile','avatar','email','sex','isconfirmed','praise','attention','fans','role'];
        $userList = D('users')->whereIn('id', $lower_user_arr)->skip($offset)->take($pagesize)->get($userFeild);
        $total = D('users')->whereIn('id', $lower_user_arr)->count();
        $totalPage = ceil($total / $pagesize);
        // 设置都是绑定
        foreach ($userList as &$value){
            $value->is_binding = 1;
            $value->avatar = getSignUrl($value->avatar);
        }
        unset($value);
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage,'list' =>$userList,]);
        //return json_success('ok', $userList);
    }

    /**
     * 修改密码
     */
    public function Updatepassword(){
        $old_password = IT('old_password',true,'请输入旧密码');
        $password = IT('password',true,'请输入密码');
        $confirm_password= IT('confirm_password',true,'请输入确认密码');
        if($password != $confirm_password) {
            return json_error('密码和确认密码不一致');
        }
        $is_record = D('admin_users')->where('id', $this->user['id'])->first(['password']);
        if(md5($old_password) != $is_record->password) {
            return json_error('旧密码不正确');
        }

        $data = [
            'password' => md5($password),
            'encrypt' => str_random(8),
            'updated_at' => time2date(),
        ];
        $rs = D('admin_users')->where('id', $this->user['id'])->update($data);
        if (!$rs) {
            return json_error('修改密码失败');
        }

        (new Log)->add($this->user,'-修改了密码');
        return json_success('ok');
    }

    /**
     * @desc 获取新人邀请活动列表
     * @return array
     */
    public function GetActivityInvitationList()
    {
        $pagesize = IT('pagesize');
        $moblie = IT('mobile');
        $id = IT('id');
        $startdate = IT('startdate'); //开始时间
        $enddate = IT('enddate'); //结束时间
        if($startdate == 'Invalid date'){
            $startdate = '';
        }
        if($enddate == 'Invalid date'){
            $enddate = '';
        }
        $where =[];
        if ($moblie) {
            $where[] = ['mobile', 'like', '%' . $moblie . '%'];
        }
        if($id){
            $where[] = ['id', 'like', '%' . $id . '%'];
        }
        //活动金额
        $reward_amount = D('activity_config')->where('status',1)->value('reward_amount');
        $user_list = User::where($where)->where('status',1)->where('share_award','>',0)->select(['id', 'mobile', 'avatar', 'name', 'share_num','role', 'share_award','created_at'])->orderBy('share_num', 'DESC')->paginate($pagesize);
        if($user_list) {
            foreach($user_list->items() as &$user) {
                $Shareholder_attribution=Shareholder::where(['mobile'=>$user->mobile,'status'=> 0])->value('ascription');
                $membership_attribution =MemberShip::where(['mobile'=>$user->mobile,'status'=> 0])->value('ascription');
                if(!empty($Shareholder_attribution)){
                    $attribution_id = $Shareholder_attribution;
                }
                if(!empty($membership_attribution)){
                    $attribution_id = $membership_attribution;
                }
                if(!empty($attribution_id)){
                    $attribution = AffiliAtion::where('id',$attribution_id)->value('locality_name');
                }
                if(!empty($startdate) && !empty($enddate)){
                    $user->share_num = User::where('parent_id',$user->id)->whereBetween('created_at',[$startdate, $enddate])->count();
                    $user->share_award = $user->share_num * $reward_amount;
                }
                $user->avatar = $user->avatar ? getSignUrl($user->avatar) : '';
                $user->ascription = !empty($attribution)? $attribution : '';
                $user->mobile = !empty($user->mobile) ? $user->mobile : '';
            }
        }
        $list = $user_list->items();
        $share_num = array_column($list,'share_num');
        array_multisort($share_num,SORT_DESC,$list);
        return json_success('ok', ['total'=>$user_list->total(),'totalPage' => $user_list->lastPage(), 'list' => $list]);
    }

    /**
     * @desc 获取新人邀请活动详情
     * @return array
     */
    public function GetActivityInvitationDetails()
    {
        $id = IT('id', true, '请选择邀请人');
        $where_arr = ['parent_id' => $id];
        $startdate = IT('startdate'); //开始时间
        $enddate = IT('enddate'); //结束时间
        $pagesize = IT('pagesize');
        if(empty($pagesize)) {
            $pagesize = 10;
        }
        $fields = ['id', 'mobile', 'avatar', 'name', 'share_num', 'share_award', 'created_at', 'reg_type', 'role', 'membership'];
        $user_list = User::select($fields)
            ->where($where_arr)
            ->where(function ($query) use($startdate,$enddate){ if(!empty($startdate) && !empty($enddate) ) {
                 $query->whereBetween('created_at',[$startdate, $enddate]);
            }})->orderBy('created_at', 'DESC')->paginate($pagesize);
        if($user_list) {
            foreach($user_list->items() as &$user) {
                $user->avatar = $user->avatar ?  getSignUrl($user->avatar) : null;
            }
        }

        return json_success('ok', ['total'=>$user_list->total(),'totalPage' => $user_list->lastPage(), 'list' => $user_list->items()]);
    }

    /**
     * @desc 奖励汇总表
     */
    public function invite_settlement_collect()
    {
        $uid = IT('uid');   // 微影号
        $mobile = IT('mobile'); // 手机号
        $page = IT('page', 1); // 页码
        $page_size = IT('pagesize', 15); // 每页数量
        $ascription = IT('ascription'); // 所属分部
        $has_settlement = IT('has_settlement');

        $where_arr =[];
        // 微影号搜索
        if($uid){
            $where_arr[] = ['ivy_invite_settlement_collect.uid', 'like', '%' . $uid . '%'];
        }

        // 所屬分部
        if($ascription) {
            $where_arr[] = ['ivy_invite_settlement_collect.ascription', '=', $ascription];
        }
        $where_arr[]  = ['users.share_num', '>', 0];
        // 手机模糊搜索
        $mobile_where = [];
        if($mobile) {
            $mobile_where[] = ['users.mobile', 'like', '%' . $mobile . '%'];
        }
        $offset = ($page-1)*$page_size;


        $settlement_info = InviteSettlement::orderBy('end_time', 'Desc')->first(['start_time', 'end_time']);

        // 历史邀请总人数
        $total_invite = User::where(['status' => 1])->sum('share_num');

        // 上一周期邀请人数
        $cycle_invite = 0;
        if($settlement_info) {
            $cycle_invite = InviteRelationLog::whereBetween('reg_time',[$settlement_info->start_time, $settlement_info->end_time])->count();
        }


        $end_time = 0;
        if($settlement_info) {
            $end_time = $settlement_info->end_time;
        }

        $fields = ['ivy_invite_settlement_collect.uid', 'users.mobile', 'total_reward_amount', 'last_settlement_time', 'users.share_num', 'users.role', 'users.membership', 'users.avatar','users.name as user_name', 'ascription'];
        if($has_settlement) {
            // 显示未结算的
            $invite_list = DB::table('ivy_invite_settlement_collect')
                ->join('users', function($join) use($mobile_where) {
                    $join->on('users.id', '=', 'ivy_invite_settlement_collect.uid')->where('users.status', 1);
                    if($mobile_where) {
                        $join->where($mobile_where);
                    }
                })
                ->join('ivy_invite_settlement', function($join) use($uid, $end_time){
                    $join->on('ivy_invite_settlement.uid', '=', 'ivy_invite_settlement_collect.uid')->where('ivy_invite_settlement.status', 0);
                    if($end_time > 0) {
                        $join->where(['end_time' => $end_time]);
                    }
                })
                ->where($where_arr)
                ->skip($offset)
                ->take($page_size)
                ->groupBy('ivy_invite_settlement_collect.uid')
                ->orderBy('ivy_invite_settlement.invite_number', 'DESC')
                ->get($fields);
            $total = DB::table('ivy_invite_settlement_collect')
                ->join('users', function($join) use($mobile_where){
                    $join->on('users.id', '=', 'ivy_invite_settlement_collect.uid')->where('users.status', 1);
                    if($mobile_where) {
                        $join->where($mobile_where);
                    }
                })
                ->join('ivy_invite_settlement', function($join) use($uid){
                    $join->on('ivy_invite_settlement.uid', '=', 'ivy_invite_settlement_collect.uid')->where('ivy_invite_settlement.status', 0);
                })
                ->where($where_arr)
                ->distinct('ivy_invite_settlement_collect.uid')
                ->count('ivy_invite_settlement_collect.uid');
        } else {
            $invite_list = DB::table('ivy_invite_settlement_collect')
                ->join('users', function($join) use($mobile_where) {
                    $join->on('users.id', '=', 'ivy_invite_settlement_collect.uid')->where('users.status', 1);
                    if($mobile_where) {
                        $join->where($mobile_where);
                    }
                })
                ->join('ivy_invite_settlement', function($join) use($uid, $end_time){
                    $join->on('ivy_invite_settlement.uid', '=', 'ivy_invite_settlement_collect.uid');
                    if($end_time > 0) {
                        $join->where(['end_time' => $end_time]);
                    }
                })
                ->where($where_arr)
                ->skip($offset)
                ->take($page_size)
                ->groupBy('ivy_invite_settlement_collect.uid')
                ->orderBy('ivy_invite_settlement.invite_number', 'DESC')
                ->get($fields);
            $total = DB::table('ivy_invite_settlement_collect')
                ->join('users', function($join) use($mobile_where){
                    $join->on('users.id', '=', 'ivy_invite_settlement_collect.uid')->where('users.status', 1);
                    if($mobile_where) {
                        $join->where($mobile_where);
                    }
                })
                 ->join('ivy_invite_settlement', function($join) use($uid, $end_time){
                    $join->on('ivy_invite_settlement.uid', '=', 'ivy_invite_settlement_collect.uid');
                    if($end_time > 0) {
                        $join->where(['end_time' => $end_time]);
                    }
                })
                ->where($where_arr)
                ->distinct('ivy_invite_settlement_collect.uid')
                ->count('ivy_invite_settlement_collect.uid');
        }

        if($invite_list) {
            foreach ($invite_list as &$invite) {
                if($invite->role == 1) {
                    $invite->identity_name = '股东';
                } elseif($invite->membership == 1) {
                    $invite->identity_name = '会员';
                } else {
                    $invite->identity_name = '普通';
                }


                $settlement_info = InviteSettlement::where(['uid' => $invite->uid, 'status' => 0])->first(['uid']);
                $invite->has_settlement = empty($settlement_info) ? 0 : 1;

                $invite->share_num = $invite->share_num ?: 0;

                $invite->last_settlement_time = $invite->last_settlement_time ? time2date($invite->last_settlement_time) : '';
                $invite->ascription_name = '';
                if($invite->ascription) {
                    $invite->ascription_name = AffiliAtion::where('id', $invite->ascription)->value('locality_name');
                }

                $invite->avatar = $invite->avatar ? getSignUrl($invite->avatar) : '';
            }
        }

        $total_page = (int)ceil($total/$page_size);

        return json_success('ok', ['total'=>$total,'totalPage' => $total_page, 'total_invite' => $total_invite, 'cycle_invite' => $cycle_invite, 'list' => $invite_list]);
    }

    /**
     * @desc 获取指定用户未结算列表
     */
    public function settlement_invite_no_reward()
    {
        $uid = (int)IT('uid', true);
        $where_arr = ['status' => 0, 'uid' => $uid];

        $fields = ['id', 'uid', 'start_time', 'end_time', 'settlement_type', 'status', 'invite_number', 'reward_amount'];
        $settlement_list = InviteSettlement::where($where_arr)->get($fields);

        $user_info = User::where(['id' => $uid])->first(['name']);

        if($settlement_list) {
            foreach($settlement_list as &$settlement) {
                $settlement->start_time = $settlement->start_time ? time2date($settlement->start_time) : '';
                $settlement->end_time = $settlement->end_time ? time2date($settlement->end_time) : '';
                $settlement->settlement_type = $settlement->settlement_type == 1 ? '周' : '月';
                $settlement->user_name = $user_info->name ?: '';
            }
        }
        return json_success('ok', [ 'list' => $settlement_list]);
    }

    /**
     * @desc 结算邀请奖励
     * @return array
     */
    public function settlement_invite_reward()
    {
        $params['id'] = IT('id', true, '请选择结算的邀请奖励');
        $params['operator_id'] = $this->user['id'];
        $rs = InviteSettlementService::settlement_invite_reward($params);
        if($rs['code'] != 0) {
            return json_error('结算失败');
        }

        (new Log)->add($this->user,'-结算邀请奖励：'.implode(',', $params['id']));
        return json_success('ok');
    }

    /**
     * @desc 结算日志列表
     */
    public function settlement_invite_reward_list()
    {
        $start_time = IT('start_time'); // 开始时间
        $end_time = IT('end_time'); // 结束时间
        $operator_id = IT('operator_id'); // 操作人ID
        $ascription = IT('ascription'); // 所属分部
        $page = (int)IT('page', 1); // 页码
        $page_size = (int)IT('page_size', 15); // 每页数量
        $mobile = IT('mobile');

        $where_arr = ['ivy_invite_settlement.status' => 1];
        if($operator_id) {
            $where_arr['ivy_invite_settlement.operator_id'] = $operator_id;
        }

        $ascription_where = [];
        if($ascription) {
            $ascription_where['ivy_invite_settlement_collect.ascription'] = $ascription;
        }

        $mobile_where = [];
        if($mobile) {
            $mobile_where[] = ['users.mobile', 'like', '%' . $mobile . '%'];
        }

        $offset = ($page-1)*$page_size;
        $fields = ['ivy_invite_settlement_collect.uid', 'users.mobile', 'ivy_invite_settlement.settlement_time', 'ivy_invite_settlement.invite_number','ivy_invite_settlement.reward_amount',
            'ivy_invite_settlement.start_time', 'ivy_invite_settlement.end_time', 'settlement_type','ivy_invite_settlement.status as settlement_status', 'users.share_num', 'users.role', 'users.membership',
            'users.avatar','users.name as user_name','ivy_invite_settlement.operator_id','ivy_invite_settlement_collect.ascription','ivy_invite_settlement_collect.total_reward_amount'
        ];

        // @todo 待优化联表查
        $settlement_list = DB::table('ivy_invite_settlement')
            ->join('users', function($join) use ($mobile_where){
                $join->on('users.id', '=', 'ivy_invite_settlement.uid')->where('users.status', 1);
                if(!empty($mobile_where)) {
                    $join->where($mobile_where);
                }
            })
            ->join('ivy_invite_settlement_collect', function($join) use($ascription_where){
                $join->on('ivy_invite_settlement_collect.uid', '=', 'ivy_invite_settlement.uid');
                if($ascription_where) {
                    $join->where($ascription_where);
                }
            })
            ->where($where_arr)
            ->where(function ($query) use($start_time,$end_time){ if(strtotime($start_time) && strtotime($end_time)) {
                $query->whereBetween('settlement_time',[strtotime($start_time), strtotime($end_time)]);
            }})
            ->skip($offset)
            ->take($page_size)
            ->orderBy('ivy_invite_settlement.id', 'DESC')
            ->get($fields);
        $total = DB::table('ivy_invite_settlement')
            ->join('users', function($join) use ($mobile_where){
                $join->on('users.id', '=', 'ivy_invite_settlement.uid')->where('users.status', 1);
                if(!empty($mobile_where)) {
                    $join->where($mobile_where);
                }
            })
            ->join('ivy_invite_settlement_collect', function($join) use($ascription_where){
                $join->on('ivy_invite_settlement_collect.uid', '=', 'ivy_invite_settlement.uid')->where($ascription_where);
            })
            ->where($where_arr)
            ->where(function ($query) use($start_time,$end_time){ if(strtotime($start_time) && strtotime($end_time)) {
                $query->whereBetween('settlement_time',[strtotime($start_time), strtotime($end_time)]);
            }})
            ->count();
        if($settlement_list) {
            foreach($settlement_list as &$settlement) {
                $settlement->settlement_time = $settlement->settlement_time ? time2date($settlement->settlement_time) : '';
                $settlement->start_time = $settlement->start_time ? time2date($settlement->start_time) : '';
                $settlement->end_time = $settlement->end_time ? time2date($settlement->end_time) : '';
                $settlement->settlement_type = $settlement->settlement_type == 1 ? '周' : '月';
                // 获取操作人的用户名
                $settlement->operator_name = AdminUser::where(['id' => $settlement->operator_id])->value('name');
                $settlement->ascription_name = '';
                if($settlement->ascription) {
                    $settlement->ascription_name = AffiliAtion::where('id', $settlement->ascription)->value('locality_name');
                }

                $settlement->identity_name = '';
                $settlement->avatar = '';

                if($settlement->role == 1) {
                    $settlement->identity_name = '股东';
                } elseif($settlement->membership == 1) {
                    $settlement->identity_name = '会员';
                } else {
                    $settlement->identity_name = '普通';
                }

                $settlement->avatar = $settlement->avatar ? getSignUrl($settlement->avatar) : '';
            }
        }

        $total_page = (int)ceil($total/$page_size);

        return json_success('ok', ['total'=>$total,'totalPage' => $total_page, 'list' => $settlement_list]);
    }
}